from django.utils.safestring import mark_safe
import copy
"""
分页工具类使用方法：

    1.视图函数
    queryset = CancelCarInfo.objects.filter(****筛选条件****)
    page_object = Pagination(request,queryset) # 根据查询页码参数设置page_param，默认名称为page
    page_queryset = page_object.page_queryset
    page_str = page_object.html()[0]
    page_info = page_object.html()[1]
    page_id_start = page_object.html()[2]
    dict = {
            "queryset":page_queryset,
            "page_str":page_str,
            "page_info":page_info,
            "page_id_start":page_id_start,
            ***其他参数***
            
        }
    return render(request,"***模版文件***.html",dict)

    2.模版
    向模版传入queryset

    3.模版页脚
    <nav  aria-label="Page navigation" style="float: left;">
    <ul class="pagination">
        {{page_info}}
    </ul>
    </nav>
    <div style="float:right;margin-top: 30px;">
        {{page_str}}
    </div>
"""

class Pagination():
    """
    分页操作
    :param request: 请求对象
    :param queryset：查询数据集,根据条件查询后传入进行分页处理
    :param page_param:查询页码参数名称，默认为page,根据页码查询参数名称设置
    :param page_size:每页显示数量，默认为10个
    :param plus:当前页码前后显示各几个，默认为5个
    :return page_str:页码字符串
    :return page_info:显示第几页共几页
    :return page_id_start:点页面的起始页码，用于计算数据序号
    """
    def __init__(self,request,queryset, page_param="page",page_size=10,plus=5):
        # 保留原有搜索参数
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param =page_param

        # 获取页码
        page = request.GET.get(page_param,"1")
        if page == 0:
            page = 1
        if page.isdecimal():
            page=int(page)
        else:
            page = 1
        self.page = page
        self.page_size = page_size
        # 获取分页数据
        self.start = (page-1)*page_size
        self.end = page*page_size
        try:
            self.page_queryset = queryset[self.start:self.end]
        except:
            self.page_queryset = queryset[0:0]


        # 计算分页数量
        self.totle_count = queryset.count()
        page_count,div = divmod(self.totle_count, page_size)
        if div:
            page_count += 1
        self.page_count = page_count

        self.plus = plus
    
    def html(self):
        # 显示前后各几页的页码
        if self.page_count <= 2*self.plus + 1:
            page_start = 1
            page_end = self.page_count+1
        else:
            if self.page <= self.plus:
                page_start = 1
                page_end = 2*self.plus + 2
            else:
                if (self.page+self.plus)>self.page_count:
                    page_start=self.page_count - 2*self.plus
                    page_end=self.page_count+1
                else:
                    page_start = self.page-self.plus
                    page_end = self.page+self.plus+1

        # html:页码
        page_str_list=[]
        

        # 首页
        self.query_dict.setlist(self.page_param,[1])
        fist_page = f'<li><a href="?{self.query_dict.urlencode()}" aria-label="Previous"><span aria-hidden="true">首页</span></a></li>'
        page_str_list.append(fist_page)

        # 上一页    
        if self.page<=1:
            self.query_dict.setlist(self.page_param,[1])
        else:
            self.query_dict.setlist(self.page_param,[self.page-1])
        prev = f'<li><a href="?{self.query_dict.urlencode()}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'
        page_str_list.append(prev)

        # 第几页
        for i in range(page_start,page_end):
            if i == self.page:
                self.query_dict.setlist(self.page_param,[i])
                ele = f'<li class="active" ><a href="?{self.query_dict.urlencode()}">{i}</a></li>'
            else:
                self.query_dict.setlist(self.page_param,[i])
                ele = f'<li><a href="?{self.query_dict.urlencode()}">{i}</a></li>'
            page_str_list.append(ele)
        
        #下一页
        if self.page>= self.page_count:
            self.query_dict.setlist(self.page_param,[self.page_count])
        else:
            self.query_dict.setlist(self.page_param,[self.page+1])
        next = f'<li><a href="?{self.query_dict.urlencode()}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'
        page_str_list.append(next)

        # 首页
        self.query_dict.setlist(self.page_param,[self.page_count])
        last_page = f'<li><a href="?{self.query_dict.urlencode()}" aria-label="Previous"><span aria-hidden="true">尾页</span></a></li>'
        page_str_list.append(last_page)

        # 生成分页数据
        # 页码
        page_str = mark_safe(''.join(page_str_list))
        # 总信息，显示第几页共几页
        page_info = mark_safe(f'<div id="page-info" style="float:right;margin-top:10px">Page {self.page} of {self.page_count} ; Title {self.totle_count}</div>')
        # 当前页面的开始编号,用于模版中计算序号
        page_id_start = (self.page-1)*self.page_size+1

        return page_info,page_str,page_id_start



    